import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:stock_check/common/dao/TasksDao.dart';
import 'package:stock_check/common/model/taskItemDetail.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';
import 'package:stock_check/common/utils/ScanUtils.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:stock_check/widget/renderTaskItemWidget.dart';

/// 资产盘点扫描
class TaskScan extends StatefulWidget {
  final List<TaskDetailItem> list;
  final int userId;
  const TaskScan({Key key, this.list, this.userId}) : super(key: key);
  @override
  _TaskScanState createState() => _TaskScanState();
}

class _TaskScanState extends State<TaskScan> with SingleTickerProviderStateMixin {
  GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  var qrText = "";
  Animation<double> animation;
  AnimationController controller;
  TaskDetailItem item;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = new AnimationController(duration: const Duration(seconds: 3), vsync: this);
    animation=CurvedAnimation(parent: controller, curve: Curves.ease);
    animation = new Tween<double>(begin: 0.0, end: 200.0).animate(controller)
      ..addListener((){
        setState(() {

        });
      });

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }

    });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    var child = Stack(
      fit: StackFit.expand,
      alignment: Alignment.bottomCenter,
      children: <Widget>[
        Container(
          width: double.infinity,
          height: CommonUtils.getScreenHeight(context)/1.5,
          child: QRView(
            key: qrKey,
            onQRViewCreated: _onQRViewCreated,
          ) ,
        ),
        Positioned(
          top: CommonUtils.getScreenHeight(context)/4,
          width: 200.0,
          height: 200.0,
          child:CustomPaint(
            size: Size(200, 200), //指定画布大小
            painter: MyPainter(),
            foregroundPainter: LinePainter(animation.value),
          ),
        ),
        Positioned(
            width: CommonUtils.getScreenWidth(context)-20,
            height: 150.0,
            bottom: 20.0,
            child: _renderItem()
        )
      ],
    );
    return StoreBuilder<StockState>(builder: (context, store) {
      return MyScaffold(
        title: Text('二维码扫描'),
        noLeading: true,
        store: store,
        child: child,
      );
    });
  }

  @override
  void dispose() {
    qrKey = null;
    controller.dispose();
    // TODO: implement dispose
    super.dispose();
  }


  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  void _onQRViewCreated(QRViewController controller) {
    final channel = controller.channel;
    controller.init(qrKey);
    channel.setMethodCallHandler((MethodCall call) async {
      switch (call.method) {
        case "onRecognizeQR":
          dynamic arguments = call.arguments;
          // 和上次一样的就忽略
          if(qrText==arguments.toString()) return;
          setState(() {
            qrText = arguments.toString();
            bool flag = false;
            for(int i=0;i<widget.list.length;i++){
              if(widget.list[i].eqptNo == qrText){
                item = widget.list[i];
                _saveData(widget.list[i]);
                flag = true;
                break;
              }
            }
            if(!flag){
              Fluttertoast.showToast(msg: '暂未找到该资产！',toastLength: Toast.LENGTH_LONG);
              item = null;
            }
            setState(() {

            });
          });
      }
    });
  }

  void _saveData(TaskDetailItem item) async{
    item.status = 2;// 确认状态
    // 更新本地盘点任务
    await TasksDao.updateTaskListByID(item);
    Fluttertoast.showToast(msg: '资产已确认,请继续扫描！',toastLength: Toast.LENGTH_LONG);
  }

  _renderItem() {
    return item != null?
    Column(
      children: <Widget>[
        RenderTaskItemWidget(item:item),
      ],
    ):
    Container(
      child: Center(
        child: Text('请扫描二维码...',style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold
        ),),
      ),
    );
  }
}


